package com.adu.music.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2016/12/2.
 */
public class EncryptUtils {

    private static final Logger logger = LoggerFactory.getLogger(EncryptUtils.class);
    private static final String AES_CBC_PADDING = "AES/CBC/PKCS5Padding";
    private static final Charset charset = Charset.forName("UTF-8");
    private static final String nonce = "0CoJUm6Qyw8W8jud";
    private static final String secKey = "y9OUHpunGAvFmwZw";
    private static final String encSecKey = "b6b775b7cfeddabcf569f1afd036f054e8c72c75ad6b7c378d678ef8396776e3826069960d1d846a4a2c7ce51232b6e978a17528d0803137f62db4edf9241c8e036633bf7a292101a01e24fe2fc2ccc69d4e0476c1eb494ce579a2613225834445e5efd9296b5aa6dc0c7a164b253b81f2de1bf65cd34e824cb77de83b32bb91";


    /**
     * 实现AES加密
     * @param text   被加密的字符串
     * @param secKey 加密密钥
     * @return 密文
     */
    private static String aesEncrypt(String text, String secKey) {
        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PADDING);
            SecretKeySpec key = new SecretKeySpec(secKey.getBytes(charset), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec("0102030405060708".getBytes(charset)));
            byte[] data = cipher.doFinal(text.getBytes(charset));
            return Base64.getEncoder().encodeToString(data);
        } catch (Exception e) {
            logger.error("aes加密异常，text:{}", text);
            throw new RuntimeException("aes加密异常", e);
        }
    }

    /**
     * 网易云音乐的aes加密请求参数方法
     * @param params 请求参数原文
     * @return 加密后的密文，格式: {"params":"","encSecKey":""}
     */
    public static Map<String, String> neteaseParamsEncrypt(String params) {
        // 先使用nonce作为密钥加密
        String encParams = aesEncrypt(params, nonce);
        // 再使用secKey进行加密一次
        encParams = aesEncrypt(encParams, secKey);
        // String encSecKey = rsaEncrypt(secKey);
        Map<String, String> resultMap = new HashMap<>(2);
        resultMap.put("params", encParams);
        resultMap.put("encSecKey", encSecKey);
        return resultMap;
    }

}
